/**
	Provides simple non-repeating random iteration for arrays, objects, and xml nodes.

	@author Chandler McWilliams
	@version 2005-11-11

	@usage
	<code>
		var looper = new RandomIterator(myData);
		while((item=looper.next()) !== false) {
			trace(looper.getCurrentKey() + ' = ' + item);
		}
	</code>

*/
class timber.collection.RandomIterator extends timber.collection.Iterator
{
	private var rnditems;
	private var repeats;
	
	public function RandomIterator(aCollection, repeats) {
		super(aCollection);
		if (repeats === true) setRepeats(true);
		rnditems = [];
		for (var i=0; i<length; i++) {
			rnditems[i] = i;
		}
	}

	public function getNextIndex() {
		if (rnditems.length == 0) {
			if (repeats) {
				rewind();
			} else {
				return false;
			}
		}
		var rnd = Math.floor(Math.random() * rnditems.length);
		var pick = rnditems[rnd];
		rnditems.splice(rnd, 1);
		return pick;
	}	

	public function getPrevIndex() {
		return getNextIndex();
	}

	public function rewind() {
		super.rewind();
		rnditems = [];
		for (var i=0; i<length; i++) {
			rnditems[i] = i;
		}
	}
	
	/**
		If set to true, the iterator will never return false, it will just keep
		providing random members from the collection.
		@param  doesRepeat Sets if the iterator repeat or end when all items are used.
	*/
	public function setRepeats(doesRepeat:Boolean):Void {
		repeats = doesRepeat;
	}

}